/****************************************************
	文件：AttributeService.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2021/1/14 21:17:5
	功能：自定义 Attribute 服务
*****************************************************/

using System;
using System.Collections.Generic;
using System.Reflection;
using HTFW.Utility;
using HTFW.Utility.Global;

namespace HTFW.Core
{
    public class AttributeService : Singleton<AttributeService>, IService
    {
        public static BindPrefabCtrl BindPrefabCtrl { get; private set; }

        List<IDisposable> mCtrlLst = new List<IDisposable>();

        public void Init(params object[] args)
        {
            BindPrefabCtrl = new BindPrefabCtrl();
            RegisterCtrl(BindPrefabCtrl);

            InitBindPrefabAttribute();
        }

        public void Dispose()
        {
            foreach (var ctrl in mCtrlLst)
                ctrl.Dispose();
            mCtrlLst.Clear();
        }

        /// <summary>
        /// 注册控制器
        /// </summary>
        /// <param name="ctrl"></param>
        void RegisterCtrl(IDisposable ctrl)
        {
            mCtrlLst.Add(ctrl);
        }

        /// <summary>
        /// 初始化 BindPrefabAttribute
        /// </summary>
        void InitBindPrefabAttribute()
        {
            Assembly assembly = Assembly.GetAssembly(typeof(BindPrefabAttribute));
            Type[] types = assembly.GetExportedTypes();

            foreach (var type in types)
            {
                foreach (Attribute attribute in type.GetCustomAttributes(true))
                {
                    if (attribute is BindPrefabAttribute data)
                    {
                        BindPrefabCtrl.Bind(type, data.Path);
                    }
                }
            }
        }
    }
}